<template>
  <div class="item">
    <el-form ref="form"
             class="item"
             :inline="true"
             :rules="rules"
             :model="item">
      <el-form-item prop="type">
        <el-select v-model="item.type"
                   @change="typeChange(item.type)"
                   class="item-select"
        >
          <el-option
            :label="$t('config.business.workOrderUserDefinedField')"
            value="customerFields">
          </el-option>
          <el-option
            :label="$t('config.business.workOrderFixedField')"
            value="fixedFields">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item prop="fieldId">
        <el-select v-model="item.fieldId"
                   @change="fieldchange"
                   class="item-select"
        >
          <el-option
            v-for="item in fieldArr"
            :key="item._id"
            :label="item.name"
            :value="item._id">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item prop="condition">
        <el-select v-model="item.condition"
                   class="item-select"
        >
          <el-option
          v-for="item in filterConditionArray"
          :key="item.value"
          :label="item.label"
          :value="item.value"
          >
          </el-option>
          <!-- <el-option
            label="不存在于"
            value="not">
          </el-option> -->
        </el-select>
      </el-form-item>
      <el-form-item prop="data">
        <el-popover
          placement="bottom"
          v-model="isShow"
          width="400"
          transition=""
          v-if="nowType !== 'single'"
          @show="showPopover"
          trigger="click">
          <tree-transfer
            ref="treeTransfer"
            :title="[$t('config.business.noOptions'),$t('config.business.haveOptions')]"
            :arrayToTree="false"
            :filter="true"
            node_key="key"
            :default-props="{label: 'name', children: 'options'}"
          >
          </tree-transfer>
          <div class="fr transfer-button" >
            <el-button
              class="primary_btn"
              @click.stop="isShow = false"
              size="mini">
              {{$t('public.cancel')}}
            </el-button>
            <el-button type="primary"
                       class="primary_btn"
                       @click.stop="saveData"
                       size="mini">
              {{$t('public.confirm')}}
            </el-button>
          </div>
          <el-input class="item-select" slot="reference" @click="isShow = true" :placeholder="dataPlaceholder"></el-input>
        </el-popover>
        <el-input v-else v-model="item.data" />
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
  import {getDicFromField} from '../../../../../utils/workflowUtils'
  import treeTransfer from '../../../../ui-modules/treeTransfer/treeTransfer'
  // import treeTransfer from 'el-tree-transfer'
  export default {
    name: 'condition-item',
    data () {
      let self = this
      // 穿梭框必填校验
      let validate = (rule, value, callback) => {
        let hasValue = Object.keys(value).some((item) => {
          return value[item].length
        })
        if (!hasValue) {
          callback(new Error(self.$t('validate.required')))
        } else {
          callback()
        }
      }
      return {
        isShow: false,
        priorityArr: [
          {name: '普通', key: '1'},
          {name: '紧急', key: '2'},
          {name: '很紧急', key: '3'}
        ],
        fromData: [],
        dicOptions: [],
        nowType:'',
        rules: {
          type: [
            {required: true, message: this.$t('validate.required'), trigger: 'change'}
          ],
          fieldId: [
            {required: true, message: this.$t('validate.required'), trigger: 'change'}
          ],
          condition: [
            {required: true, message: this.$t('validate.required'), trigger: 'change'}
          ],
          data: [
            {validator: validate, trigger: 'blur'}
          ]
        },
        conditionArray:[
        {
          label:this.$t('configLazyLoad.businessConfig.in'),
          value:'in',
          unexistin:['single']
        },
        {
          label:this.$t('configLazyLoad.businessConfig.not'),
          value:'not',
          unexistin:['single']
        },
        {
          label:this.$t('configLazyLoad.businessConfig.equal'),
          value:'equal',
          existin:['single']
        },
        {
          label:this.$t('configLazyLoad.businessConfig.unequal'),
          value:'notEqual',
          existin:['single']
        },
        {
          label:this.$t('configLazyLoad.businessConfig.contain'),
          value:'contain',
          existin:['single']
        },
        {
          label:this.$t('configLazyLoad.businessConfig.notContain'),
          value:'notContain',
          existin:['single']
        },
        {
          label:this.$t('configLazyLoad.businessConfig.startWith'),
          value:'startWith',
          existin:['single']
        },
        {
          label:this.$t('configLazyLoad.businessConfig.endWith'),
          value:'endWith',
          existin:['single']
        }
        ]
      }
    },
    props: {
      // {type: '字段类型', fieldId: '字段id', fieldName: ‘’, condition: '条件类型', data: 条件数据}
      item: {type: Object, default: function () { return {} }},
      allAgent: {type: Array, default: function () { return [] }}
    },
    inject: ['busType'],
    computed: {
      fieldArr () {
        if (this.item.type === 'customerFields') {
          // 自定义字段
          return this.flowFieldsArr
        } else if (this.item.type === 'fixedFields') {
          // 固定字段
          return [{name: this.$t('business.businessCreate'), _id: 'createUser'}, {name: this.$t('business.priorityLabel'), _id: 'priority'}]
        } else {
          return []
        }
      },
      dataPlaceholder () {
        let data = this.item.data || {}
        let labels = []
        for (let i in data) {
          data[i].some((item) => {
            let label = getLabelsById(item, this.dicOptions)
            if (label) {
              labels.push(label)
            }
            // 只展示前三个数据
            if (labels.length > 2) {
              return true
            }
          })
          if (labels.length > 2) {
            break
          }
        }
        return labels.join(',')
      },
      // 自定义字段
      flowFieldsArr () {
        let arr = ['checkbox','radio','dropdown','dropdownTree','single']
        return this.$store.state.config.businessConfig[this.busType].allFields.filter((item) => {
          return arr.indexOf(item.type)>-1 && item.enable === 'yes'
          // 'date',"datetime","multi",'number'
          // return item.type === 'checkbox' || item.type === 'radio' || item.type === 'dropdown' || item.type === 'dropdownTree' || item.type === "single"
        })
      },
      filterConditionArray(){
        let type = this.nowType
        if(type){
          return this.conditionArray.filter(item=>{
            if(item.existin){
              return  item.existin.indexOf(type)>-1
            }else{
              return item.unexistin.indexOf(type) == -1
            }
          })
        }else{
          return [{
          label:this.$t('configLazyLoad.businessConfig.in'),
          value:'in',
        },
        {
          label:this.$t('configLazyLoad.businessConfig.not'),
          value:'not',
        }]
        }
      }
    },
    components: {
      treeTransfer
    },
    watch: {
      'item.fieldId' (cur) {
        this.fieldchange(cur, this.item.data, true)
      },
      item () {
        this.$refs.form.clearValidate()
      }
    },
    methods: {
      // 穿梭框保存
      saveData () {
        this.isShow = false
        let arr = this.$refs.treeTransfer.self_to_data
        if(this.nowType !== 'single'){
          this.item.data = getKey(arr, {}, 0, this.item.fieldId)
        }
        this.item.fieldName = Object.keys(this.item.data) || []
        this.$refs.form.validate((valid) => {})
      },
      // 提交校验
      submit () {
        let data = null
        // dic不存在，清空item.data的旧值
        if (!this.dicOptions.length && !this.item.data) {
          this.item.data = ''
        }
        this.$refs.form.validate((valid) => {
          if (valid) {
            data = this.item
          }
        })
        return data
      },
      // 字段类型改变
      typeChange () {
        this.item.fieldId = ''
        this.item.condition = ''
        this.item.data = ''
        this.isShow = false
      },
      // 字段改变
      fieldchange (value, data, flag) {
        this.nowType = ''
        if (value === 'createUser') {
          this.dicOptions = this.allAgent
        } else if (value === 'priority') {
          this.dicOptions = this.priorityArr
        } else if (value) {
          let field = this.flowFieldsArr.filter((one) => {
            return this.item.fieldId === one._id
          })[0] || {}
          this.nowType = field.type
          // 工单字段类型改变成input/textarea等
          if (!field._id) {
            this.typeChange()
            this.$message.error(this.$t('config.business.tip13'))
          }
          let dic = getDicFromField(field, this.$getCache('custTmpls'), this.$getCache('options')) || {}
          this.dicOptions = dic.options || []
          if (field.type === 'checkbox' || field.type === 'radio') {
            // 如果是多选或单选，只取字典的第一级
            this.dicOptions = this.dicOptions.map(({name, key}) => {
              return {name, key}
            })
          }
        } else {
          this.dicOptions = []
        }
        if (!data) {
          this.item.data = void(0)
        }
        if(!flag)this.item.condition = ''
        this.isShow = false

      },
      ceshi(){
        console.log(this.dicOptions)
      },
      showPopover () {
        let data = this.item.data || {}
        let toData = []
        for (let i in data) {
          toData = toData.concat(data[i])
        }
        // 生成穿梭框需要的数据（加pid）, 筛选出toData中的叶子节点
        generateFromDataAndToData(this.dicOptions, 0, toData)
        // this.fromData = JSON.parse(JSON.stringify(this.dicOptions))
        this.$refs.treeTransfer.setCheckdkeys(this.dicOptions, toData)
        console.log(this.dicOptions, toData)
      }
    },
    beforeMount () {
      this.fieldchange(this.item.fieldId, this.item.data, true)
    }
  }
  let generateFromDataAndToData = function (options, pId, toData) {
    for (let i = 0; i < options.length; i++) {
      let optionItem = options[i]
      let nextOptions = optionItem.options || []
      if (nextOptions.length !== 0) {
        generateFromDataAndToData(nextOptions, optionItem.key, toData)
        let position = toData.indexOf(optionItem.key)
        if (position !== -1) {
          toData.splice(position, 1)
        }
      }
      optionItem.pid = pId
    }
  }
  let getKey = function (options, obj = {}, index = 0, fieldId) {
    let field = index ? (fieldId + '_' + index) : fieldId
    if (!obj[field]) {
      obj[field] = []
    }
    for (let i = 0; i < options.length; i++) {
      let optionItem = options[i]
      let nextOptions = optionItem.options || []
      obj[field].push(optionItem.key)
      if (nextOptions.length !== 0) {
        let cascade = index + 1
        getKey(nextOptions, obj, cascade, fieldId)
      }
    }
    return obj
  }
  function getLabelsById (id, source) {
    let flag = false
    for (let index = 0; index < source.length; index++) {
      let item = source[index]
      if (id === item.key) {
        flag = true
        return item.name
      }
    }
    if (!flag) {
      for (let index = 0; index < source.length; index++) {
        let name = getLabelsById(id, source[index].options || [])
        if (name) {
          return name
        }
      }
    }
  }
</script>

<style scoped lang='stylus'>
  .item
    display inline-block
  .item-select
    width 180px
    padding-right:5px
  .transfer-button
    padding-top 15px
</style>
